package demo4.controller;

import demo4.mapper.IUserMapper;
import demo4.mapper.UserMapper;
import demo4.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Scanner;

@Component
public class UserController {
    @Autowired
    private IUserMapper iUserMapper;

    public void start(){
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入序号:");
        System.out.println("1:用户注册");
        System.out.println("2:用户登录");
        System.out.println("3:修改密码");
        System.out.println("4:查询用户列表");

        int num= sc.nextInt();
        switch (num){
            case 1:
                regUser();
                break;
            case 2:
                loginUser();
                break;
            case 4:
                listUser();
                break;

        }
    }

    private void listUser(){
        System.out.println("用户列表");
        List<UserInfo> userList=iUserMapper.selectAll();
        for (UserInfo userInfo:userList){
            System.out.println(userList);
        }
    }
    private void regUser(){
        System.out.println("UserController:开始用户注册....");
        System.out.println("欢迎注册");
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username=sc.nextLine();
        System.out.println("请输入密码:");
        String password=sc.nextLine();
        System.out.println("请输入昵称:");
        String nickname=sc.nextLine();
        System.out.println("请输入年龄:");
        int age=sc.nextInt();
        //如果一切没有问题，应当将该信息插入到数据库保存
        UserInfo userInfo=new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setNickname(nickname);
        userInfo.setAge(age);
        //将用户数据交给UserMapper保存
        int num=iUserMapper.insert(userInfo);
        System.out.println(num);
        System.out.println(num>0?"恭喜您注册成功了":"注册失败");
    }
    private void loginUser(){
        System.out.println("UserMapper:开始用户登录....");
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username=scanner.nextLine();
        System.out.println("请输入密码:");
        String password=scanner.nextLine();

        //首先根据用户登录时输入的用户名查询该用户信息
        UserInfo userInfo= iUserMapper.selectByusername(username);
        if(userInfo!=null){//有无该用户
            //比较密码
            if(userInfo.getPassword().equals(password)){//密码一致登录成功
                System.out.println("登录成功，欢迎["+userInfo.getNickname()+"]回来");
            }else{
                System.out.println("密码输入有误!");
            }
        }else {//用户名错误
            System.out.println("该用户不存在！");

        }


    }


}
